package com.yonyou.gmmc.gateway.app.filter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.marketing.common.AppResponse;
import org.marketing.common.util.CheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yonyou.gmmc.gateway.app.service.AppServiceInterface;

@Service
public class AccessFilter extends ZuulFilter {

	private static Logger log = LoggerFactory.getLogger(AccessFilter.class);
	
	@Autowired
	private AppServiceInterface appServiceInterface;
	
	@Value("${FILTER_IGNORE}")
    private String filterIgnore;

	@Override
	public Object run() {
		log.info("------进入gateway------");
		RequestContext ctx = RequestContext.getCurrentContext();

		HttpServletRequest request = ctx.getRequest();
		HttpServletResponse res = ctx.getResponse(); 
		
		String uri = request.getRequestURI();
		
		String accessToken = request.getParameter("accessToken");
        log.info("accessToken==============>> " + accessToken);
        String userId = request.getParameter("userId");
        log.info("userId==============>> " + userId);
        
        String[] Ignore = filterIgnore.split(",");
        for(String str : Ignore){
            if(uri.indexOf(str)>0){
                log.warn("---登录之前无需验证Token");
                return null;
            }
        }
        
        if(CheckUtil.NullOrEmpty(accessToken)){
            log.warn("没有token---sign not pass");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            return null;
        }
        
        if(CheckUtil.NullOrEmpty(userId)){
            log.warn("没有userId---sign not pass");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            return null;
        }
        
        AppResponse<Boolean> result = appServiceInterface.checkAccessTokenExpire(accessToken, userId);
        if(!result.getData()){
            log.warn("token不在有效期---sign not pass");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(500);
            return null;
        }
        
		return null;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}
}
